package com.clickpaas.governmentcloud.service.policymatchextservice.impl;

import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.*;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ConstantSuggest;
import com.clickpaas.governmentcloud.common.EnumCompanyType;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtService;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 上海市级企业技术中心认定政策匹配
 * @date 2020/12/16 10:31 上午
 */
@Slf4j
@Service
public class EnterpriseTechCenterServiceImpl implements MatchExtService {

    @Resource
    private PolicyCondCal policyCondCal;

    /**
     * 跟政策是否匹配
     * @param policy 政策对象
     * @return ServerResponse<?>
     */
    @Override
    public ServerResponse<?> isMatchSuccess(PolicyEntity policy) {
        /**
         * 建议
         */
        StringBuffer suggest = new StringBuffer();
        /**
         * 返回信息
         */
        ServerResponse<?> serverResponse = ServerResponse.createError(ConstantExt._ERROR_MESSAGE);
        /**
         * 评分
         */
        Integer score = ConstantExt._ZERO;
        /**
         *  必要条件判断
         */
        HashMap hashMap = necessCondi(policy);
        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        /**
         * 必要条件对快速匹配数据做处理（精确匹配、快速匹配）
         */
        boolean ifNecess=Boolean.parseBoolean(hashMap.get(ConstantExt._NECESS).toString());
        if(!ifNecess && isQuickMatch){
            return serverResponse;
        }

        /**
         * 累加必要条件评分
         */
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());

        HashMap suggAndScore = getScore(policy);
        /**
         * 累加评分
         */
        score = score + Integer.parseInt(suggAndScore.get(ConstantExt._SCORE).toString());
        /**
         * 评分为0，快速匹配不展示数据
         */
        if(score <= 0 && isQuickMatch){
            return serverResponse;
        }
        /**
         * 添加建议
         */
        suggest.append(suggAndScore.get(ConstantExt._SUGGEST).toString());
        /*if (suggest.length() == 0 && score >= 90) {
            suggest.append("建议申报");
        }*/

        /**
         * 快速匹配不添加建议
         */
        if (isQuickMatch){
            suggest = new StringBuffer();
        }
        /**
         * 必要条件不满足得0分
         */
        if(!ifNecess){
            score = 0;
        }
        return insertPolicyData(policy,score,suggest,serverResponse);
    }

    /**
     * 计算企业评分
     *
     * @param policy
     * @return
     */
    @Override
    public HashMap getScore(PolicyEntity policy) {
        HashMap<String, Object> returnValue = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        StringBuffer suggest = new StringBuffer();
        /**
         * 研发人员
         */
        if (null != policy.getDpersonnel()
                && policy.getDpersonnel()>=60){
            score +=10;
        }else {
            suggest.append(ConstantSuggest._TECH_INNOV_RD_PERSONNEL);
        }

        boolean flag_industry = false;
        /**
         * 企业新增投资20000万元以上 && 已承担国家、本市重点项目
         */
        if (null != policy.getInvestAmount()
                && policy.getInvestAmount()>=20000
                && null != policy.getUndertakeKeyProjects()
                && ConstantExt._NEGA.equals(policy.getUndertakeKeyProjects())){
            score +=10;
        }else {
            flag_industry = true;
        }

        /**
         * 去年研发费
         */
        if (null != policy.getDexpensesLastYear()
                && policy.getDexpensesLastYear()>=1000){
            score +=10;
        }else {
            suggest.append(ConstantSuggest._CENTER_RD_EXPENSES);
        }

        /**
         * 去年研发占比
         */
        if(policyCondCal.RDPerCostRateLastYear(policy)>=3){
            score +=10;
        }else {
            suggest.append(ConstantSuggest._CENTER_RD_RATIO);
        }

        /**
         * I、II知识产权数目
         */
        if(policyCondCal.IntellPropertyFirst(policy)+policyCondCal.IntellPropertySecond(policy)>=6){
            score +=15;
        }else {
            suggest.append(ConstantSuggest._CENTER_INTELLECTUAL);
        }

        /**
         * 企业类型
         */
        List list = typeOfCompany(policy);
        if(null != list
                && list.contains(EnumCompanyType._PRODUCERSERVICES.getCompanyTypeEng())){
            /**
             * 生产性服务业企业：上一年度主营业务收入不低于2亿元
             */
            if(null != policy.getBusinessIncomeOfLastYear()
                    && policy.getBusinessIncomeOfLastYear()>20000){
                score += 10;
            }else {
                if (!flag_industry){
                    suggest.append(ConstantSuggest._CENTER_INDUSTRY_AMOUNT);
                }
            }
            /**
             * 生产性服务业企业：研发设备原值≧600万
             */
            if(null != policy.getEquipmentOriginalValue()
                    && policy.getEquipmentOriginalValue()>600){
                score += 15;
            }else {
                suggest.append(ConstantSuggest._CENTER_EQUIPMENT);
            }
        }else {
            /**
             * 其他企业：上一年度主营业务收入不低于3亿元
             */
            if(null != policy.getBusinessIncomeOfLastYear()
                    && policy.getBusinessIncomeOfLastYear()>30000){
                score += 10;
            }else {
                if (!flag_industry){
                    suggest.append(ConstantSuggest._CENTER_INDUSTRY_AMOUNT);
                }
            }
            /**
             * 其他企业：研发设备原值≧1000万
             */
            if(null != policy.getEquipmentOriginalValue()
                    && policy.getEquipmentOriginalValue()>1000){
                score += 15;
            }else {
                suggest.append(ConstantSuggest._CENTER_EQUIPMENT);
            }
        }
        returnValue.put(ConstantExt._SCORE,score);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }

    /**
     * 写入匹配结果
     *
     * @param policy
     * @return
     */
    @Override
    public ServerResponse insertPolicyData(PolicyEntity policy,Integer score,StringBuffer suggest,ServerResponse serverResponse) {

        /**
         * 查询当前政策信息
         */
        TPoliciesDTO policyInfo = policyCondCal.getPolicyInfo(ConstantExt._ENTERPRISE_TECH_CENTER);

        if (null == policyInfo) {
            log.info("政策：【{}】查询不到",ConstantExt._ENTERPRISE_TECH_CENTER);
            return serverResponse;
        }
        policyCondCal.insertCommonPolicyData(policy, policyInfo, score, suggest);
        return ServerResponse.createSuccess(ConstantExt._SUCCESS_MESSAGE);
    }

    /**
     * 判断公司类型
     * @param policy
     * @return
     */
    public List typeOfCompany(PolicyEntity policy){
        ArrayList<String> typeComStr = new ArrayList<>();
        if(null == policy.getIndustrys()) {
            return null;
        }
        List<String> industrys = policy.getIndustrys();
        for (String indu : industrys){
            if(indu.equals(EnumCompanyType._PRODUCERSERVICES.getCompanyTypeChina())){
                typeComStr.add(EnumCompanyType._PRODUCERSERVICES.getCompanyTypeEng());
            }
        }
        return typeComStr;
    }

    /**
     * 必要条件(精确匹配)
     * @param policy
     * @return
     */
    @Override
    public HashMap necessCondi(PolicyEntity policy){
        HashMap<String, Object> map = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        map.put(ConstantExt._NECESS,true);
        StringBuffer suggStr = new StringBuffer();
        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        /**
         * 快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
         */
        if (isQuickMatch && null == policy.getDishonesty()){
            score += 5;
        }else {
            /**
             * 是否违法
             */
            if(!policyCondCal.isIllegal(policy)){
                map.put(ConstantExt._NECESS,false);
            }else {
                score += 5;
            }
        }

        /**
         * 快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
         */
        if (isQuickMatch && null == policy.getConformDevelopmentOrientation()){
            score += 5;
        }else {
            /**
             * 产业方向
             */
            if (!ConstantExt._YES.equals(policy.getConformDevelopmentOrientation())) {
                map.put(ConstantExt._NECESS, false);
            } else {
                score += 5;
            }
        }
        /**
         * 快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
         */
        if (isQuickMatch && null == policy.getIndustrialRanking()){
            score += 5;
        }else {
            /**
             * 行业地位
             */
            if (!ConstantExt._TOP5.equals(policy.getIndustrialRanking())){
                map.put(ConstantExt._NECESS,false);
            }else {
                score += 5;
            }
        }
        /**
         * 快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
         */
        if (isQuickMatch
                && ( null == policy.getEnterpriseQualification()
                || policy.getEnterpriseQualification().size()<=0 )){
            score += 5;
        }else {
            /**
             * 区级企业技术中心 资质
             */
            if (null != policy.getEnterpriseQualification() && policy.getEnterpriseQualification().size()>0) {
                if (policy.getEnterpriseQualification().contains(EnumCompanyType._DISTENTERTECHCENTER.getCompanyTypeChina())){
                    score += 5;
                }else {
                    map.put(ConstantExt._NECESS, false);
                }
            } else {
                map.put(ConstantExt._NECESS, false);
            }
        }

        /**
         * 必要条件建议追加
         */
        if (!Boolean.parseBoolean(map.get(ConstantExt._NECESS).toString())){
            suggStr.append(ConstantSuggest._CENTER_NECESSARY);
        }
        map.put(ConstantExt._SCORE,score);
        map.put(ConstantExt._SUGGEST,suggStr);
        return map;
    }
}
